package com.fks.fks_service.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESUtil {

    public static Base64.Encoder encoder = Base64.getEncoder();
    public static Base64.Decoder decoder = Base64.getDecoder();

    public static final String aesKey = "zyW2KwYzErquO2MNIi2Gt7skk1Hr3XekmuwwAbWCe2j=";// 注意平台分配的 key 需要加一个=结尾

    // 将 json 字符串 str，用 aesKey 加密，然后 Base64
    public static String encrypt(String str) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] secretKey = decoder.decode(aesKey.getBytes());
        SecretKey keySpec = new SecretKeySpec(secretKey, "AES");
        byte[] iv = new byte[16];
        System.arraycopy(secretKey, 0, iv, 0, 16);

        cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv));
        byte[] aesData = cipher.doFinal(str.getBytes());
        return new String(encoder.encode(aesData), "UTF-8");
    }

    // 将 Base64 后的加密 str，解开并解密，得到 json 字符串
    public static String decrypt(String str) throws Exception {
        byte[] secretKey = decoder.decode(aesKey.getBytes());
        byte[] iv = new byte[16];
        System.arraycopy(secretKey, 0, iv, 0, 16);

        byte[] data = decoder.decode(str.getBytes());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKey keySpec = new SecretKeySpec(secretKey, "AES");
        IvParameterSpec ivps = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivps);
        return new String(cipher.doFinal(data), "UTF-8");
    }

}